package flc.ast.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;

import com.blankj.utilcode.util.FlashlightUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.google.android.exoplayer2.util.ColorParser;
import com.otaliastudios.cameraview.CameraListener;
import com.otaliastudios.cameraview.CameraOptions;
import com.otaliastudios.cameraview.VideoResult;
import com.otaliastudios.cameraview.controls.Flash;
import com.otaliastudios.cameraview.controls.Mode;
import com.otaliastudios.cameraview.size.SizeSelector;
import com.otaliastudios.cameraview.size.SizeSelectors;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import flc.ast.BaseAc;
import flc.ast.R;
import flc.ast.databinding.ActivityVideoShootBinding;
import stark.common.basic.utils.DensityUtil;
import stark.common.basic.utils.FileP2pUtil;
import stark.common.basic.utils.StkPermissionHelper;
import stark.common.basic.utils.WorkPathUtil;

public class VideoShootActivity extends BaseAc<ActivityVideoShootBinding> {

    private boolean isLight = false, isDelay = false, isChu = false;
    private Handler mhandler;
    private int mTakeTime;

    @Override
    protected int onCreate() {
        return R.layout.activity_video_shoot;
    }

    @Override
    protected void initView() {
        mDataBinding.ivVideoShootBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        mDataBinding.ivVideoShootStart.setOnClickListener(this);
        mDataBinding.ivVideoShootLight.setOnClickListener(this);
        mDataBinding.ivVideoShootDelay.setOnClickListener(this);
        mDataBinding.llContainer.setOnClickListener(this);
        mDataBinding.ivVideoShootChu.setOnClickListener(this);
        mhandler = new Handler();
        mTakeTime = 0;
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.ivVideoShootStart:
                if (mDataBinding.cameraView.isTakingVideo()) {
                    mDataBinding.cameraView.stopVideo();
                } else {
                    String filePath = WorkPathUtil.generateVideoFilePath(null);
                    if (isDelay) {
                        new Thread(() -> {
                            int time=3;
                            while (time!=0) {
                                try {
                                    // 每隔1秒执行一次
                                    int finalTime = time;
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            mDataBinding.tvDelay.setVisibility(View.VISIBLE);
                                            mDataBinding.tvDelay.setText(finalTime +"");
                                        }
                                    });
                                    time--;
                                    Thread.sleep(1000);
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }
                            }
                        }).start();
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                mDataBinding.tvDelay.setVisibility(View.GONE);
                                if (filePath != null) {
                                    mDataBinding.cameraView.takeVideoSnapshot(new File(filePath));
                                }
                            }
                        }, 3000);
                    } else {
                        if (filePath != null) {
                            mDataBinding.cameraView.takeVideoSnapshot(new File(filePath));
                        }
                    }
                }
                break;
            case R.id.ivVideoShootLight:
                if (isLight) {
                    isLight = false;
                    mDataBinding.cameraView.setFlash(Flash.OFF);
                    mDataBinding.ivVideoShootLight.setImageResource(R.drawable.shanguangdeng2);
                } else {
                    isLight = true;
                    mDataBinding.cameraView.setFlash(Flash.TORCH);
                    mDataBinding.ivVideoShootLight.setImageResource(R.drawable.shanguangdeng1);
                }
                break;
            case R.id.ivVideoShootDelay:
                if (isDelay) {
                    isDelay = false;
                    mDataBinding.ivVideoShootDelay.setImageResource(R.drawable.yanshiguan1);
                } else {
                    isDelay = true;
                    mDataBinding.ivVideoShootDelay.setImageResource(R.drawable.s3);
                }
                break;
            case R.id.ivVideoShootChu:
                if (isChu) {
                    isChu = false;
                    mDataBinding.ivVideoShootChu.setImageResource(R.drawable.chupingpai1);
                } else {
                    isChu = true;
                    mDataBinding.ivVideoShootChu.setImageResource(R.drawable.chupingpai2);
                }
                break;
            case R.id.llContainer:
                if (isChu) {
                    if (mDataBinding.cameraView.isTakingVideo()) {
                        mDataBinding.cameraView.stopVideo();
                    } else {
                        String filePath = WorkPathUtil.generateVideoFilePath(null);
                        if (isDelay) {
                            new Thread(() -> {
                                int time=3;
                                while (time!=0) {
                                    try {
                                        // 每隔1秒执行一次
                                        int finalTime = time;
                                        runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                mDataBinding.tvDelay.setVisibility(View.VISIBLE);
                                                mDataBinding.tvDelay.setText(finalTime +"");
                                            }
                                        });
                                        time--;
                                        Thread.sleep(1000);
                                    } catch (InterruptedException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }).start();
                            new Handler().postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    if (filePath != null) {
                                        mDataBinding.cameraView.takeVideoSnapshot(new File(filePath));
                                    }
                                }
                            }, 3000);
                        } else {
                            if (filePath != null) {
                                mDataBinding.cameraView.takeVideoSnapshot(new File(filePath));
                            }
                        }
                    }
                }
                break;
        }
    }

    @Override
    protected void initData() {
        getPermission();
    }

    private void getPermission() {
        StkPermissionHelper.permission(Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO).reqPermissionDesc(getString(R.string.get_camera_permission)).callback(new StkPermissionHelper.ACallback() {
            @Override
            public void onGranted() {
                //初始化相机
                initCameraView();
            }

            @Override
            public void onDenied(boolean needGoSettings) {
                ToastUtils.showShort(R.string.no_permission);
            }
        }).request();
    }

    //初始化相机
    private void initCameraView() {
        mDataBinding.cameraView.setMode(Mode.PICTURE);
        mDataBinding.cameraView.setLifecycleOwner(this);
        int width = DensityUtil.getWith(mContext);
        int height = DensityUtil.getHeight(mContext);
        SizeSelector maxAreaSelector = SizeSelectors.maxArea(width * height);
        SizeSelector equalWidthSelector = SizeSelectors.withFilter(size -> size.getWidth() == width);
        mDataBinding.cameraView.setPictureSize(SizeSelectors.and(maxAreaSelector, equalWidthSelector));
        mDataBinding.cameraView.addCameraListener(new CameraListener() {
            @Override
            public void onCameraOpened(@NonNull CameraOptions options) {
                super.onCameraOpened(options);
            }

            @Override
            public void onVideoRecordingStart() {
                //开始
                mDataBinding.tvVideoShootTime.setText("0s");
                startRecordTime();
            }

            @Override
            public void onVideoRecordingEnd() {
                //结束
                mDataBinding.tvVideoShootTime.setText("");
                stopRecordTime();
            }

            @Override
            public void onVideoTaken(@NonNull VideoResult result) {
                String videoPath = result.getFile().getPath();
                TakeCompActivity.videoPath = videoPath;
                ToastUtils.showShort(R.string.take_complete);
                FileP2pUtil.copyPrivateVideoToPublic(mContext, result.getFile().getPath());
            }
        });
    }

    //开始拍摄
    private void startRecordTime() {
        mTakeTime = 0;
        mhandler.removeCallbacks(mUpdateRecordTimeTask);
        mhandler.postDelayed(mUpdateRecordTimeTask, 1000);
    }

    //结束拍摄
    private void stopRecordTime() {
        mhandler.removeCallbacks(mUpdateRecordTimeTask);
    }

    private final Runnable mUpdateRecordTimeTask = new Runnable() {
        @Override
        public void run() {
            mTakeTime++;
            mDataBinding.tvVideoShootTime.setText(mTakeTime + "s");
            mhandler.postDelayed(mUpdateRecordTimeTask, 1000);
        }
    };

}